<?php


namespace app\common\cachemodel;


use app\common\lib\Util;
use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

/**
 * 活动模型
 * Class ZhunleActivity
 * @package app\common\cachemodel
 */
class ZhunleActivity extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_activity';

    protected $cacheModel = 'active.active';

    /**
     * 获取当前商品类型的所有活动
     * @param $goods_type
     * @return array
     * @throws \Exception
     */
    public function getGoodsActivingList($goods_type)
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $goods_type)->setSort('desc')->ZsGetIocData('list', function () use ($goods_type)
        {
            //活动只有折扣类型
            $where = ['gtype' => $goods_type, 'status' => 1, 'type' => 1];
            try
            {
                $ids = $this->where($where)->order('id', 'DESC')->column('id', 'id');
                $ids = array_flip_key_value($ids);
            }
            catch (\Exception $e)
            {
                $ids = [];
            }
            return $ids;
        });
        return $this->batchGetInfoByIds($ids);
    }

    /**
     * 获取多个商品活动信息
     * @param $goodsType
     * @param $goods
     * @param string $startTime
     * @throws \app\common\lib\exception\ApiException
     */
    public function goodsActiveInfo($goodsType, &$goods, $startTime = '')
    {
        $goodsType = (int)$goodsType;
        $time = time();
        $gids = array_column($goods, 'id');
        $now_time = time();
        //获取当前商品所有开启的活动信息
        $actives = $this->getGoodsActivingList($goodsType);
        foreach ($actives as $active)
        {
            $active = is_array($active) ? $active : json_decode($active, true);
            if ((int)$active['gtype'] !== $goodsType) continue;
            //判断活动时间是否在有效范围内
            if ($active['start_time'] <= $now_time && $active['end_time'] >= $now_time)
            {
                $isHaveActive = false;
                //冥想活动只根据类型判断
                if ($active['gtype'] === 29)
                {
                    $isHaveActive = true;
                    $actingGids = array_column($goods, 'id');
                } else
                {
                    //获取参与活动的gid
                    $acGids = $active['gids'] ? explode(',', $active['gids']) : [];
                    $actingGids = array_intersect($acGids, $gids);//当前参与活动的gid
                    if ($actingGids)
                    {
                        //获取活动的拓展信息
                        $active['extend'] = $extend = $active['extend'] ? json_decode($active['extend'], true) : [];
                        //若是运势则判断当前运势时间是否在活动有效范围内
                        if ($startTime && in_array($goodsType, [2, 3, 4], true))
                        {
                            //运势时间格式重组
                            $start_time = Util::FormatFortuneTime($goodsType, $startTime)['start_time'];
                            //若是购买运势则判断当前购买时间是否打折
                            $frotune_start = $extend['fortune_start_time'] ?? 0;//若假则默认为0
                            $frotune_end = $extend['fortune_end_time'] ?? $start_time + 99;//若假则默认比当前时间大
                            if ($start_time >= $frotune_start && $start_time <= $frotune_end)
                            {
                                $isHaveActive = true;
                            }
                        } else
                        {
                            $isHaveActive = true;
                        }
                    }
                }

                if ($isHaveActive)
                {
                    $countDown = $active['end_time'] - $time;
                    foreach ($actingGids as $gid)
                    {
                        if ((int)$active['type'] === 2)
                        {
                            $price = $active['attr'];
                        } else
                        {
                            $price = (float)(sprintf("%.2f", $goods[$gid]['now_prize'] * $active['attr']));
                        }
                        $goods[$gid]['active'] = [
                            'id' => $active['id'],
                            'name' => $active['name'],
                            'des' => $active['des'],
                            'type' => $active['type'],
                            'attr' => $active['attr'],
                            'end_time' => $active['end_time'],
                            'count_down' => max($countDown, 0),
                            'price' => $price,//优惠后的最终价格
                        ];
                    }
                }
                $gids = array_diff($gids, $actingGids);//剩余未参与当前活动的gid
            }
        }
    }

    /**
     * 获取指定商品信息 正在进行的活动信息
     * @param int $goods_type
     * @param int $gid
     * @param string $start_time
     * @return array
     * @throws \Exception
     */
    public function getActivingGood($goods_type, $gid = 0, $start_time = '')
    {
        $now_time = time();
        //获取当前商品所有开启的活动信息
        $actives = $this->getGoodsActivingList($goods_type);
        foreach ($actives as $active)
        {
            $active = is_array($active) ? $active : json_decode($active, true);
            //判断活动时间是否在有效范围内
            if ($active['start_time'] <= $now_time && $active['end_time'] >= $now_time)
            {
                //获取参与活动的gid
                $gids = $active['gids'] ? explode(',', $active['gids']) : [];
                //获取活动的拓展信息
                $active['extend'] = $extend = $active['extend'] ? json_decode($active['extend'], true) : [];
                switch (true)
                {
                    case $goods_type == 5://若当前是幸运之城则不根据gid
                        return $active;
                        break;
                    case in_array($goods_type, [2, 3, 4])://若是运势则判断当前运势时间是否在活动有效范围内
                        //运势时间格式重组
                        if ($start_time)
                        {
                            $start_time = Util::FormatFortuneTime($goods_type, $start_time)['start_time'];
                            if (in_array($gid, $gids))
                            {
                                //若是购买运势则判断当前购买时间是否打折
                                $frotune_start = $extend['fortune_start_time'] ?? 0;//若假则默认为0
                                $frotune_end = $extend['fortune_end_time'] ?? $start_time + 99;//若假则默认比当前时间大
                                if ($start_time >= $frotune_start && $start_time <= $frotune_end)
                                {
                                    return $active;
                                }
                            }
                        }
                        return null;
                    default:
                        if (in_array($gid, $gids))
                        {
                            return $active;
                        }
                        break;
                }
            }
        }
        return null;
    }

    /**
     * 根据id批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'gids,name,des,type,attr,start_time,end_time,extend,gtype,condition,status';
        try
        {
            $data = $this->where(['id' => ['in', $ids]])->order('id', 'DESC')->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
